package org.huangrui.juc.day04.sync;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁/递归锁
 *
 * @Author hr
 * @Create 2024-03-31 13:31
 */
public class T04_ReentrantLock {
    public synchronized void add() {
        add();
    }

    public static void main(String[] args) {
        // Lock演示可重入锁
        Lock lock = new ReentrantLock();
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " 外层");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " 中层");
                    lock.lock();
                    try {
                        System.out.println(Thread.currentThread().getName() + " 内层");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "AA").start();

        new Thread(() -> {
            lock.lock();
            System.out.println("aaaaa");
            lock.unlock();
        }, "BB").start();
        // synchronized
        // new T04_ReentrantLock().add();
        Object o = new Object();
        new Thread(() -> {
            synchronized (o) {
                System.out.println(Thread.currentThread().getName() + " 外层");
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + " 中层");
                    synchronized (o) {
                        System.out.println(Thread.currentThread().getName() + " 内层");
                    }
                }
            }
        }, "t1").start();
    }
}
